package com.bungarus.codec.ssl;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

public class SSLEngineFactory {
    private static final SSLEngineFactory factory = new SSLEngineFactory();
    private KeyManagerFactory keyManagerFactory;

    public static SSLEngineFactory getInstance() {
        return factory;
    }

    private SSLEngineFactory(){
        init();
    }

    public KeyManagerFactory getKeyManagerFactory() {
        return keyManagerFactory;
    }

    private void init() {
        InputStream inputStream = null;
        try {
            inputStream = SSLKeyStore.getStoreStream();

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(inputStream, SSLKeyStore.getStorePwd());

            keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, SSLKeyStore.getCertificatePwd());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if(null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static final class SSLKeyStore {
        private static final String DEFAULT_KEY_STORE_PATH = "bungarus.jks";
        private static final String EXTERNAL_KEY_STORE_PATH = "/home/bungarus.jks";
        private static final String SYS_KEY_STORE = "ks";
        private static final String SYS_KEY_STORE_PWD = "ksp";
        private static final String SYS_CERT_PWD = "certp";

        public static InputStream getStoreStream() {
            InputStream keyStoreInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_KEY_STORE_PATH);
            if(null == keyStoreInputStream) {
                try {
                    keyStoreInputStream = new FileInputStream(System.getProperty(SYS_KEY_STORE, EXTERNAL_KEY_STORE_PATH));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            return keyStoreInputStream;
        }

        public static char[] getStorePwd() {
            return System.getProperty(SYS_KEY_STORE_PWD).toCharArray();
        }

        public static char[] getCertificatePwd() {
            return System.getProperty(SYS_CERT_PWD).toCharArray();
        }
    }
}
